<?php
if (!function_exists('getOrderFromRedisByOrderid')) {
    /**
     * 根据order_id从redis获取数据，redis中找不到则去数据库找
     * @param  string $order_id
     * @return 找不到数据返回null, 否则返回 json 字符串
     */
    function getOrderFromRedisByOrderid($order_id)
    {
        //根据orderid从redis读取订单数据
        $CI =& get_instance();
        $CI->load->library('RedisDriver', 'redisdriver');
        $CI->redisdriver->connect();
        $orderData = $CI->redisdriver->getStr('order_'.$order_id);
        //在redis找不到则去数据库找
        if(empty($orderData))
        {
        	$CI->load->model('Order_model', 'order_model');
	        $CI->load->model('Orderdetail_model');
            //获取订单数据
            $order = $CI->order_model->getOrderById($order_id);
            if(empty($order))
            {
                return null;
            }
            //获取订单详情数据
            $orderDetailData = $CI->Orderdetail_model->getOrderDetailByOrderid($order['order_id']);
            $order_detail = array();
            foreach ($orderDetailData as $key => $value) {
                $order_detail[] = array('goods_id' => $value['goods_id'], 
                                    'amount' => $value['amount'],
                                    'activity_id' => $value['activity_id'],
                                    'price' => $value['price'],//单价
                                    'update_time' => $value['update_time'],
                                    'status' => $value['status'],//未发货
                                    'order_id' => $value['order_id']
                                    );
            }
            //组装成json
            $orderData = json_encode(array('order' => $order, 'order_detail' => $order_detail));
        }
        return $orderData;
    }
}

if (!function_exists('delOrderFromRedisByOrderid')) {
    /**
     * 根据order_id删除对应的redis订单数据
     * @param  int $order_id 订单号
     */
    function delOrderFromRedisByOrderid($order_id)
    {
        $CI =& get_instance();
        $CI->load->library('RedisDriver', 'redisdriver');
        $CI->redisdriver->connect();

        $key = 'order_' . $order_id;
        if(! empty($CI->redisdriver->getStr($key)))
        {
            $CI->redisdriver->delStr($key);
        }
    }
}